<?php

namespace App\Admin\Forms\User;

use App\Http\Controllers\Api\Repositories\WxContRepositories;
use App\Models\WxChat;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class UserChatReplyForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * 处理表单请求.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {

        $id = $input['id'];
        $content = $input['content'];
        $img = $input['img'];
        if(_empty_($id)){
            return $this->response()
                ->error('参数错误');
        }

        if(_empty_($content) && _empty_($img)){
            return $this->response()
                ->error('参数错误');
        }

        $chat = WxChat::find($id);
        $oid = $chat->user_id;
        $uid = $chat->object_id;
        $model = WxContRepositories::add($uid, $oid, $content, $img, '', '', 0);
        if($model){

            $websocket_id = GatewayUtils::uid2client_id($oid);
            if($websocket_id){
                GatewayUtils::success($websocket_id, 5, ['chat_content'=>_mini_emoji($content, true), 'chat_image'=>$img,
                    'from_user'=>UserUtils::get_cached_user($uid) ]);
            }

            return $this->response()
                ->success('回复成功.')
                ->refresh();
        }

        return $this->response()
            ->error('回复失败.');
    }

    /**
     * 构建表单.
     */
    public function form()
    {
        $this->html(function (){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">以被聊天的身份向发起人聊天</div>';
        }, '');
        $this->hidden('id')->value($this->payload["id"]);

        $this->textarea('content', "内容");
        $this->image('img', '图片')->help('不能同时发内容和图片')->url('files/uploads')->uniqueName()->autoUpload();
    }

}
